<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/9/17
 * Time: 13:39
 * 私人订制订单
 */

namespace app\api\controller;


use think\Db;

class Privateorder extends Base
{
    public $user_id;
    public $create_time;
    public $page;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 私人订制皮肤
     * @return \think\response\Json
     */
    public function skin(){
        $skin = Db::table('up_private_skin')
            ->where('pskin_status', 1)
            ->field('pskin_id, pskin_name')
            ->select();

        if($skin){
            return json(['status' => 200, 'msg' => $skin]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 套餐图片
     * po_id    订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setMealImage(){
        $po_id = input('po_id');
        $images = Db::table('up_private_order')
            ->join('up_private_setmeal', 'po_setmeal_id = ps_id', 'LEFT')
            ->where('po_id', $po_id)
            ->field('ps_pf_img, ps_mj_img')
            ->find();
        return json(['status' => 200, 'msg' => $images]);
    }
    
    /**
     * 皮肤配置选项
     * @return \think\response\Json
     * pskin_id      皮肤ID
     */
    public function skinConfig(){
        $pskin_id = input('pskin_id');
        $config = Db::table('up_private_skin_config')
            ->where('psc_pskin_id', $pskin_id)
            ->where('psc_status', 1)
            ->field('psc_id, psc_name')
            ->select();
        if($config){
            return json(['status' => 200, 'msg' => $config]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 客户最新一条收货信息回显
     * client_id      客户ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showAddress(){
        $client_id = input('client_id');
        $address = Db::table('up_private_order')
            ->join('up_area ua1', 'ua1.district_id = po_sheng', 'LEFT')
            ->join('up_area ua2', 'ua2.district_id = po_shi', 'LEFT')
            ->join('up_area ua3', 'ua3.district_id = po_qu', 'LEFT')
            ->where('po_client_id', $client_id)
            ->field('po_sheng, po_shi, po_qu, po_receive_username, po_receive_phone, po_address, 
            ua1.district sheng, ua2.district shi, ua3.district qu')
            ->order('po_time desc')
            ->find();
        if($address){
            return json(['status' => 200, 'msg' => $address]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 判断是否有库存
     * setMeal_id    套餐ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setMealStock(){
        $po_setmeal_id = input('setMeal_id');
        $stock = Db::table('up_private_stock')
            ->where(['stock_user_id' => $this->user_id, 'stock_ps_id' => $po_setmeal_id])
            ->field('stock_number, stock_id')
            ->find();
        if(!$stock || $stock['stock_number'] <= 0) {
            return json(['status' => 0, 'msg' => '库存不足，请先购买']);
        }else{
            return json(['status' => 200, 'msg' => true]);
        }

    }
    
    /**
     * 提交私人订制订单
     * @return \think\response\Json
     * order
     *      po_client_id           客户ID
     *      po_setmeal_id          套餐ID
     *      po_images              皮肤图集
     *      po_mj_images           魔镜图集
     *      po_for                 1 为自己订制   2 为他人订制
     *      po_receive_username    收件人姓名
     *      po_receive_phone       收件人手机号
     *      po_sheng               省
     *      po_shi                 市
     *      po_qu                  区
     *      po_address             详细地址
     *      po_num                 订制数量
     *      skin                   皮肤详情
     *          pos_ps_id          皮肤ID
     *          pos_psc_id         皮肤选项ID，逗号隔开
     *          pos_describe       描述
     */
    public function commitPrivateOrder(){
        $order = input('order');
        $order = json_decode($order, true);
        $po_client_id = $order['po_client_id'];
        $po_setmeal_id = $order['po_setmeal_id'];
        $po_images = $order['po_images'];
        $po_mj_images = $order['po_mj_images'];
        $po_for = $order['po_for'];
        $po_receive_username = $order['po_receive_username'];
        $po_receive_phone = $order['po_receive_phone'];
        $po_sheng = $order['po_sheng'];
        $po_shi = $order['po_shi'];
        $po_qu = $order['po_qu'];
        $po_address = $order['po_address'];
        $po_num = isset($order['po_num']) ? $order['po_num'] : 1;
        $skin = $order['skin'];
        $order_number = date('YmdHis') . rand(1000, 9999);

        // 库存
        $stock = Db::table('up_private_stock')
            ->where(['stock_user_id' => $this->user_id, 'stock_ps_id' => $po_setmeal_id])
            ->field('stock_number, stock_id')
            ->find();
        if(!$stock || $stock['stock_number'] < $po_num) return json(['status' => 0, 'msg' => '库存不足，请先购买']);
        
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_rule')->find();
//        if($user['user_private_stock'] <= 0 && $user['user_rule'] == 2){
//            return json(['status' => 0, 'msg' => '可用库存不足，请联系管理员']);
//        }
        
        if($user['user_rule'] != '1' && $user['user_rule'] != '2'){ // 统一用户（脖脸皮用户）
            $po_type = 1;
        }else{
            $po_type = 2;
        }
        
        // 订单二维码
        try{
            $qrcode = $this->getOrderQrcode($order_number);
        }catch(\Exception $e){
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
        
        Db::startTrans();
        try{
            // 插入私人订制订单表
            $insert_order = [
                'po_number' => $order_number,
                'po_user_id' => $this->user_id,
                'po_client_id' => $po_client_id,
                'po_setmeal_id' => $po_setmeal_id,
                'po_images' => $po_images,
                'po_mj_images' => $po_mj_images,
                'po_for' => $po_for,
                'po_type' => $po_type,
                'po_receive_username' => $po_receive_username,
                'po_receive_phone' => $po_receive_phone,
                'po_sheng' => $po_sheng,
                'po_shi' => $po_shi,
                'po_qu' => $po_qu,
                'po_address' => $po_address,
                'po_qrcode' => $qrcode,
                'po_num' => $po_num,
                'po_time' => $this->create_time
            ];
            $po_id = Db::table('up_private_order')->insertGetId($insert_order);
            
            // 插入私人订制订单皮肤表
            if(is_array($skin) && !empty($skin)){
                $insert_skin = [];
                foreach($skin as $k => $v){
                    $insert_skin[$k] = [
                        'pos_po_id' => $po_id,
                        'pos_ps_id' => $v['pos_ps_id'],
                        'pos_psc_id' => $v['pos_psc_id'],
                        'pos_describe' => $v['pos_describe']
                    ];
                }
                Db::table('up_private_order_skin')->insertAll($insert_skin);
            }

            // 减库存
            Db::table('up_private_stock')->where('stock_id', $stock['stock_id'])->dec('stock_number', $po_num)->update();
            
            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功', 'po_id' => $po_id]);
        }catch(\Exception $ex){
            Db::rollback();
            return json(['status' => 0, 'msg' => $ex->getMessage()]);
        }
    }
    
    /**
     * 私人订制订单----用户端
     * @return \think\response\Json
     * keyword         搜索关键字
     * po_status       状态   0 全部   1 待审核   2 已审核   4 已配货   5 已发货   6 售后
     * page            页码
     */
    public function userPrivateOrderList(){
        $keyword = trim(input('keyword'), ' ');
        $po_status = input('po_status'); // 0 全部   1 待审核   2 已审核   4 已配货   5 已发货   6 售后
        
        $where['po_user_id'] = $this->user_id;
        $where['po.po_type'] = 1;
        if(isset($keyword) && $keyword != ''){
            $where['pc.pc_client_name|po.po_number'] = ['like', '%' . $keyword . '%'];
        }
        if($po_status != 0){
            if($po_status == 2){
                $where['po_cate'] = 1;
                $where['po_status'] = ['between', [2, 3]];
            }else{
                if($po_status == 6){
                    $where['po_cate'] = 2;
                    $where['po_status'] = 2;
                }else{
                    $where['po_status'] = $po_status;
                }
            }
           
        }
        
        $list = Db::table('up_private_order')->alias('po')
            ->join('up_private_client pc', 'pc.pc_id = po.po_client_id', 'LEFT')
            ->join('up_private_setmeal ps', 'ps.ps_id = po.po_setmeal_id', 'LEFT')
            ->where($where)
            ->field('po.po_id, po.po_number, po.po_status, pc.pc_client_name, pc.pc_client_phone, 
            pc.pc_client_age, pc.pc_client_gender, pc.pc_client_marry, ps.ps_name, po.po_time, po_qrcode, 
            po_pid, po_cate, po_is_sale, po_setmeal_id')
            ->order('po.po_time desc')
            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
     }
    
    /**
     * 订单详情
     * @return \think\response\Json
     * po_number      订单编号---H5页面
     * po_id          订单ID---APP
     */
    public function orderDetail(){
        header("Access-Control-Allow-Origin: *");
        $po_number = input('po_number');
        $po_id = input('po_id');
        
        $where = [];
        if(isset($po_number) && $po_number != '') $where['po_number'] = $po_number; // H5
        if(isset($po_id) && $po_id != '') $where['po_id'] = $po_id; // APP
        
        $order = Db::table('up_private_order')->alias('po')
            ->join('up_private_client pc', 'pc.pc_id = po.po_client_id', 'LEFT')
            ->join('up_private_setmeal ps', 'ps.ps_id = po.po_setmeal_id', 'LEFT')
            ->join('up_area ua1', 'po.po_sheng = ua1.district_id', 'LEFT')
            ->join('up_area ua2', 'po.po_shi = ua2.district_id', 'LEFT')
            ->join('up_area ua3', 'po.po_qu = ua3.district_id', 'LEFT')
            ->where($where)
            ->field('po.po_id, po.po_number, po.po_status, po.po_time, pc.pc_client_name, pc.pc_client_phone, 
            pc.pc_client_age, pc.pc_client_gender, pc.pc_client_marry, ps.ps_name, po.po_images, po.po_mj_images, 
            po.po_receive_username, po.po_receive_phone, po.po_address, ua1.district sheng, ua2.district shi, 
            ua3.district qu, po.po_wl_number, po.po_wl_company, po.po_wl_remark, po.po_wl_images, po.po_effect, 
            po.po_remind, po.po_refuse_reason, po.po_use_explain, po.po_qrcode')
            ->find();
        if($order['po_images']){
            $order['po_images'] = explode(',', $order['po_images']);
        }else{
            $order['po_images'] = [];
        }
        if($order['po_mj_images']){
            $order['po_mj_images'] = explode(',', $order['po_mj_images']);
        }else{
            $order['po_mj_images'] = [];
        }
        if($order['po_wl_images']){
            $order['po_wl_images'] = explode(',', $order['po_wl_images']);
        }else{
            $order['po_wl_images'] = [];
        }
        
        // 皮肤
        $skin = Db::table('up_private_order_skin')
            ->join('up_private_skin', 'pskin_id = pos_ps_id', 'LEFT')
            ->where('pos_po_id', $order['po_id'])
            ->field('pskin_name, pos_psc_id, pos_describe')
            ->select();
        if($skin){
            foreach($skin as $k => $v){
                $psc = Db::table('up_private_skin_config')
                    ->where('psc_id', 'IN', $v['pos_psc_id'])
                    ->column('psc_name');
                $skin[$k]['config_name'] = $psc;
            }
        }
        $order['skin'] = $skin;
        // 配货信息
        $peihuo = Db::table('up_private_order_peihuo')
            ->join('up_private_product', 'pp_id = pop_pp_id', 'LEFT')
            ->where('pop_po_id', $order['po_id'])
            ->column('pp_name');
            
        $peihuo_str = implode(',', $peihuo);
//        if($peihuo){
//            foreach($peihuo as $kp => $vp){
//                $peihuo_str .= $vp['pp_name'] . ' ' . $vp['pp_spec'] . '×' . $vp['pop_number'] . ',';
//            }
//            $peihuo_str = rtrim($peihuo_str, ',');
//        }
        $order['peihuo'] = $peihuo_str;
        return json(['status' => 200, 'msg' => $order]);
    }
    
    /**
     * 待审核订单列表---审核员端
     * @return \think\response\Json
     * keyword        关键字
     * po_status      订单状态    1 待审核   2 待配货（配货员） 3 待配货（审核员）  4 待发货  5 已发货
     * page           页码
     */
    public function adminOrderList(){
        $keyword = trim(input('keyword'), ' ');
        $po_status = input('po_status');
//        $where['po_status'] = 1;
        $where['po_type'] = 1;
        
        if($po_status == 3){
            $where['po_status'] = ['between', [2, 3]];
        }elseif($po_status == 5){
            $where['po_status'] = ['between', [5, 6]];
        }else{
            $where['po_status'] = $po_status;
        }
        
        if(isset($keyword) && $keyword != '') $where['pc.pc_client_name|po.po_number'] = ['like', '%' . $keyword . '%'];
        
        $list = Db::table('up_private_order')->alias('po')
            ->join('up_u_user u', 'po.po_user_id = u.user_id', 'LEFT')
            ->join('up_private_client pc', 'pc.pc_id = po.po_client_id', 'LEFT')
            ->join('up_private_setmeal ps', 'ps.ps_id = po.po_setmeal_id', 'LEFT')
            ->where($where)
            ->field('po.po_id, po.po_number, po.po_status, pc.pc_client_name, pc.pc_client_phone, 
            pc.pc_client_age, pc.pc_client_gender, pc.pc_client_marry, ps.ps_name, po.po_time, 
            u.user_username, u.user_phone, po_pid, po_cate, po_is_sale')
            ->order('po.po_time desc')
            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 订单详情---审核员端
     * @return \think\response\Json
     * po_id       订单ID
     */
    public function checkOrderDetail(){
        $po_id = input('po_id');
        $where['po_id'] = $po_id;
    
        $order = Db::table('up_private_order')->alias('po')
            ->join('up_private_client pc', 'pc.pc_id = po.po_client_id', 'LEFT')
            ->join('up_private_setmeal ps', 'ps.ps_id = po.po_setmeal_id', 'LEFT')
            ->join('up_u_user uuu', 'uuu.user_id = po.po_user_id', 'LEFT')
            ->join('up_area ua1', 'po.po_sheng = ua1.district_id', 'LEFT')
            ->join('up_area ua2', 'po.po_shi = ua2.district_id', 'LEFT')
            ->join('up_area ua3', 'po.po_qu = ua3.district_id', 'LEFT')
            ->where($where)
            ->field('po.po_id, po.po_number, po.po_status, po.po_time, pc.pc_client_name, pc.pc_client_phone, 
            pc.pc_client_age, pc.pc_client_gender, pc.pc_client_marry, ps.ps_name, po.po_images, po.po_mj_images, 
            po.po_receive_username, po.po_receive_phone, po.po_address, ua1.district sheng, ua2.district shi, 
            ua3.district qu, po.po_wl_number, po.po_wl_company, po.po_wl_remark, po.po_wl_images, po.po_effect, 
            po.po_remind, uuu.user_username, uuu.user_phone, uuu.user_shop_name, po.po_refuse_reason, po.po_use_explain, 
            po_pid, po_cate, po_is_sale')
            ->find();
        if($order['po_images']){
            $order['po_images'] = explode(',', $order['po_images']);
        }else{
            $order['po_images'] = [];
        }
        if($order['po_mj_images']){
            $order['po_mj_images'] = explode(',', $order['po_mj_images']);
        }else{
            $order['po_mj_images'] = [];
        }
        if($order['po_wl_images']){
            $order['po_wl_images'] = explode(',', $order['po_wl_images']);
        }else{
            $order['po_wl_images'] = [];
        }
    
        // 皮肤
        $skin = Db::table('up_private_order_skin')
            ->join('up_private_skin', 'pskin_id = pos_ps_id', 'LEFT')
            ->where('pos_po_id', $order['po_id'])
            ->field('pskin_name, pos_psc_id, pos_describe')
            ->select();
        if($skin){
            foreach($skin as $k => $v){
                $psc = Db::table('up_private_skin_config')
                    ->where('psc_id', 'IN', $v['pos_psc_id'])
                    ->column('psc_name');
                $skin[$k]['config_name'] = $psc;
            }
        }
        $order['skin'] = $skin;
        // 配货信息
        $peihuo = Db::table('up_private_order_peihuo')
            ->join('up_private_product', 'pp_id = pop_pp_id', 'LEFT')
            ->where('pop_po_id', $order['po_id'])
            ->column('pp_name');
        $peihuo_str = implode(',', $peihuo);
//        if($peihuo){
//            foreach($peihuo as $kp => $vp){
//                $peihuo_str .= $vp['pp_name'] . ',';
//            }
//            $peihuo_str = rtrim($peihuo_str, ',');
//        }
        $order['peihuo'] = $peihuo_str;
        return json(['status' => 200, 'msg' => $order]);
    }
    
    /**
     * 审核通过
     * @return \think\response\Json
     * po_id       订单ID
     */
    public function checkAgree(){
        $po_id = input('po_id');
        $update = [
            'po_id' => $po_id,
            'po_status' => 2,
            'po_check_time' => $this->create_time
        ];
        $res = Db::table('up_private_order')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 审核拒绝
     * @return \think\response\Json
     * po_id      订单ID
     * refuse_reason   拒绝原因
     */
    public function checkRefuse(){
        $po_id = input('po_id');
        $po_refuse_reason = input('refuse_reason');
        $order = Db::table('up_private_order')->where('po_id', $po_id)->field('po_user_id, po_status')->find();
        if($order['po_status'] == 3) return json(['status' => 0, 'msg' => '请不要重复提交']);
        
        Db::startTrans();
        try{
            // 修改订单状态
            $update = [
                'po_id' => $po_id,
                'po_status' => 3,
                'po_refuse_reason' => $po_refuse_reason,
                'po_check_time' => $this->create_time
            ];
            Db::table('up_private_order')->update($update);
            
            // 增加用户库存
            Db::table('up_u_user')->where('user_id', $order['po_user_id'])->setInc('user_private_stock');
            
            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 待配货列表
     * @return \think\response\Json
     * keyword      关键字
     * page         页码
     */
    public function unPeihuo(){
        $keyword = trim(input('keyword'), ' ');
        $where['po_status'] = 2;
        $where['po_type'] = 1;
    
        if(isset($keyword) && $keyword != '') $where['pc.pc_client_name|po.po_number'] = ['like', '%' . $keyword . '%'];
    
        $list = Db::table('up_private_order')->alias('po')
            ->join('up_u_user uuu', 'uuu.user_id = po.po_user_id', 'LEFT')
            ->join('up_private_client pc', 'pc.pc_id = po.po_client_id', 'LEFT')
            ->join('up_district ud', 'ud.dis_id = uuu.user_district_id', 'LEFT')
            ->where($where)
            ->field('po.po_id, po.po_number, uuu.user_shop_name, uuu.user_username, uuu.user_phone, 
            pc.pc_client_name, ud.dis_name, po.po_time')
            ->order('po.po_time desc')
            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 套餐下的产品列表
     * @return \think\response\Json
     * po_id      订单ID
     */
    public function setmealProduct(){
        $po_id = input('po_id');
        $order = Db::table('up_private_order')->where('po_id', $po_id)->field('po_setmeal_id')->find();
        
        $product = Db::table('up_private_product')
            ->where('pp_ps_id', $order['po_setmeal_id'])
            ->where('pp_status', 1)
            ->field('pp_id, pp_name, pp_spec')
            ->select();
        if($product){
            return json(['status' => 200, 'msg' => $product]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 配货
     * @return \think\response\Json
     * data
     *      po_effect     效果
     *      po_remind     注意事项
     *      po_use_explain 使用说明
     *      po_id         订单ID
     *      product       产品
     *          pp_id      产品ID
     *          number     数量
     */
    public function peihuo(){
        $data = input('data');
        $data = json_decode($data, true);
        $po_effect = $data['po_effect'];
        $po_remind = $data['po_remind'];
        $po_use_explain = $data['po_use_explain'];
        $po_id = $data['po_id'];
        $product = $data['product'];

        $order = Db::table('up_private_order')->where('po_id', $po_id)->field('po_status')->find();
        if($order['po_status'] == 4) return json(['status' => 0, 'msg' => '请不要重复提交配货信息']);
        
        Db::startTrans();
        try{
            // 更新订单表
            $update = [
                'po_id' => $po_id,
                'po_status' => 4,
                'po_remind' => $po_remind,
                'po_effect' => $po_effect,
                'po_use_explain' => $po_use_explain,
                'po_peihuo_time' => $this->create_time
            ];
            Db::table('up_private_order')->update($update);
            
            // 插入配货表
            if(isset($product) && is_array($product) && $product != ''){
                $product_all = [];
                foreach($product as $k => $v){
                    $product_all[$k] = [
                        'pop_po_id' => $po_id,
                        'pop_pp_id' => $v['pp_id'],
                        'pop_number' => $v['number']
                    ];
                }
                Db::table('up_private_order_peihuo')->insertAll($product_all);
            }
            
            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 发货
     * @return \think\response\Json
     * po_id          订单ID
     * po_wl_number   物流编号
     * po_wl_company  物流公司
     * po_wl_remark   物流备注
     * po_wl_images   物流图片
     */
    public function sendProduct(){
        $po_id = input('po_id');
        $po_wl_number = trim(input('po_wl_number'), ' ');
        $po_wl_company = input('po_wl_company');
        $po_wl_remark = input('po_wl_remark');
        $po_wl_images = input('po_wl_images');
        
        $update = [
            'po_id' => $po_id,
            'po_status' => 5,
            'po_wl_number' => $po_wl_number,
            'po_wl_company' => $po_wl_company,
            'po_wl_remark' => $po_wl_remark,
            'po_wl_images' => $po_wl_images,
            'po_send_time' => $this->create_time
        ];
        $res = Db::table('up_private_order')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 确认收货
     * @return \think\response\Json
     * po_id     私人订制订单ID
     */
    public function confirmOrder(){
        $po_id = input('po_id');
        $res = Db::table('up_private_order')
            ->update(['po_id' => $po_id, 'po_status' => 6, 'po_over_time' => $this->create_time]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 物流
     * @return \think\response\Json
     * po_id     订单ID
     */
    public function wuLiu(){
        $po_id = input('po_id');
        // 订单
        $order = Db::table('up_private_order')
            ->join('up_area u1', 'u1.district_id = po_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = po_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = po_qu', 'LEFT')
            ->field('po_wl_number, po_wl_company, po_number, po_time, po_send_time, u1.district sheng, 
            u2.district shi, u3.district qu, po_address, po_receive_username, po_receive_phone')
            ->where('po_id', $po_id)
            ->find();
        
        // 物流信息
        //*********** 获取快递公司编码
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $order['po_wl_number'],
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能判断返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['status' => 0, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';
            
            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $order['po_wl_number'] . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['status' => 0, 'msg' => $search_data['message'], 'order' => $order/*, 'address' => $address*/]);
                }else{
                    return json(['status' => 200, 'msg' => $search_data['data'], 'order' => $order/*, 'address' => $address*/]);
                }
            }else{
                return json(['status' => 200, 'msg' => [], 'order' => $order/*, 'address' => $address*/]);
            }
        }
    }

    //***********************************************   新增需求   *************************************//

    /**
     * 订单是否支持售后
     * order_id       订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function canAfterSale(){
        $order_id = input('order_id');
        $order = Db::table('up_private_order')->where('po_id', $order_id)->field('po_status, po_cate')->find();
        if($order['po_status'] != 5 && $order['po_status'] != 6){
            return json(['status' => 0, 'msg' => '该订单状态不支持售后']);
        }
        if($order['po_cate'] == 2){
            return json(['status' => 0, 'msg' => '该订单类型不支持售后']);
        }
        return json(['status' => 200, 'msg' => true]);
    }

    /**
     * 提交私人订制订单售后订单
     * @return \think\response\Json
     * order
     *      order_id               订单号
     *      po_setmeal_id          套餐ID
     *      po_images              图集
     *      po_mj_images           魔镜图片
     *      skin                   皮肤详情
     *          pos_ps_id          皮肤ID
     *          pos_psc_id         皮肤选项ID，逗号隔开
     *          pos_describe       描述
     */
    public function applyAfterSale(){
        $order = input('order');
        $order = json_decode($order, true);
        $po_setmeal_id = $order['po_setmeal_id'];
        $po_images = $order['po_images'];
        $po_mj_images = $order['po_mj_images'];
        $skin = $order['skin'];
        $order_id = $order['order_id'];
        $order_number = 'SH_' . date('YmdHis') . rand(1000, 9999);

        // 订单二维码
        try{
            $qrcode = $this->getOrderQrcode($order_number);
        }catch(\Exception $e){
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }

        $order = Db::table('up_private_order')
            ->where('po_id', $order_id)
            ->field('po_client_id, po_receive_username, po_receive_phone, po_sheng, po_shi, po_qu, po_address, 
            po_type')
            ->find();

        Db::startTrans();
        try{
            // 插入私人订制订单表
            $insert_order = [
                'po_number' => $order_number,
                'po_user_id' => $this->user_id,
                'po_client_id' => $order['po_client_id'],
                'po_setmeal_id' => $po_setmeal_id,
                'po_status' => 2,
                'po_images' => $po_images,
                'po_mj_images' => $po_mj_images,
                'po_type' => $order['po_type'],
                'po_receive_username' => $order['po_receive_username'],
                'po_receive_phone' => $order['po_receive_phone'],
                'po_sheng' => $order['po_sheng'],
                'po_shi' => $order['po_shi'],
                'po_qu' => $order['po_qu'],
                'po_address' => $order['po_address'],
                'po_qrcode' => $qrcode,
                'po_time' => $this->create_time,
                'po_pid' => $order_id,
                'po_cate' => 2
            ];
            $po_id = Db::table('up_private_order')->insertGetId($insert_order);

            // 插入私人订制订单皮肤表
            if(is_array($skin) && !empty($skin)){
                $insert_skin = [];
                foreach($skin as $k => $v){
                    $insert_skin[$k] = [
                        'pos_po_id' => $po_id,
                        'pos_ps_id' => $v['pos_ps_id'],
                        'pos_psc_id' => $v['pos_psc_id'],
                        'pos_describe' => $v['pos_describe']
                    ];
                }
                Db::table('up_private_order_skin')->insertAll($insert_skin);
            }

            // 修改原订单类型
            Db::table('up_private_order')->where('po_id', $order_id)->setField('po_is_sale', 2);

            Db::commit();
            return json(['status' => 200, 'msg' => '提交成功', 'po_id' => $po_id]);
        }catch(\Exception $ex){
            Db::rollback();
            return json(['status' => 0, 'msg' => $ex->getMessage()]);
        }
    }

    /**
     * 客户订单列表
     * client_id       客户ID
     * page            页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function clientOrder(){
        $client_id = input('client_id');
        $keyword = input('keyword');
        $where['po_client_id'] = $client_id;
        $where['po_cate'] = 1;
        if(isset($keyword) && $keyword != ''){
            $where['po_number'] = ['LIKE', '%' . $keyword . '%'];
        }
        $order = Db::table('up_private_order')
            ->join('up_private_setmeal ps', 'ps.ps_id = po_setmeal_id', 'LEFT')
            ->where($where)
            ->field('po_id, po_number, po_status, ps.ps_name, po_time, po_is_sale')
            ->order('po_time desc')
            ->page($this->page, 10)
            ->select();
        if($order){
            return json(['status' => 200, 'msg' => $order]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 根据原订单号，查看售后订单列表
     * order_id     订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function afterOrderList(){
        $order_id = input('order_id');

        $list = Db::table('up_private_order')->alias('po')
            ->join('up_private_client pc', 'pc.pc_id = po.po_client_id', 'LEFT')
            ->join('up_private_setmeal ps', 'ps.ps_id = po.po_setmeal_id', 'LEFT')
            ->where('po_cate', 2)
            ->where('po_pid', $order_id)
            ->field('po.po_id, po.po_number, po.po_status, pc.pc_client_name, pc.pc_client_phone, 
            pc.pc_client_age, pc.pc_client_gender, pc.pc_client_marry, ps.ps_name, po.po_time, po_qrcode')
            ->order('po.po_time desc')
//            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
}